<script setup>
import { ref, onMounted } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import { HomeFilled, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'

// 返回首页
const router = useRouter()
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

// 收藏数据
const collections = ref([])
const loading = ref(false)

// 获取收藏对话
const fetchCollections = async () => {
    loading.value = true
    try {
        // 从localStorage获取学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        if (!username) {
            ElMessage.error('用户未登录')
            return
        }

        // 请求后端API获取收藏
        const response = await axios.get('/api/student/collections/', {
            params: { username }
        })

        // 将返回的收藏保存
        collections.value = response.data || []

        console.log('获取到收藏数据:', collections.value)
    } catch (error) {
        console.error('获取收藏失败:', error)
        ElMessage.error('获取收藏列表失败，请稍后重试')

        // 使用测试数据
        collections.value = [
            {
                id: 1,
                title: "数据结构中的树和图",
                content: "问：树和图有什么区别？\n\n答：树和图都是非线性数据结构，但有几个关键区别：\n1. 树是一种特殊的图，它是无环连通图\n2. 树中任意两个节点之间有且仅有一条路径\n3. 树有一个根节点，图没有特定的根\n4. 图可以有环路，树不能有环\n5. 图的边可以是有向或无向的，树的边通常表示为有向的（从父到子）",
                created_at: "2025-04-10T10:25:00Z"
            },
            {
                id: 2,
                title: "机器学习算法比较",
                content: "问：常见的机器学习算法有哪些，各有什么适用场景？\n\n答：常见机器学习算法及适用场景：\n1. 线性回归：数值预测，关系简单直接\n2. 逻辑回归：二分类问题，需要概率输出\n3. 决策树：分类和回归，可解释性强\n4. 随机森林：高维数据，防过拟合\n5. SVM：小样本高维分类，边界明确\n6. K-means：无监督聚类，簇数已知\n7. 神经网络：复杂模式识别，大数据量",
                created_at: "2025-04-15T14:30:00Z"
            },
            {
                id: 3,
                title: "操作系统内存管理",
                content: "问：虚拟内存是什么，有什么作用？\n\n答：虚拟内存是一种内存管理技术，它将物理内存和磁盘空间结合使用，创造一个看似连续的大容量内存空间。主要作用：\n1. 扩展物理内存容量，允许运行更大的程序\n2. 内存保护，进程只能访问自己的虚拟地址空间\n3. 简化内存分配，程序看到连续地址空间\n4. 支持共享内存，多进程可访问同一物理内存\n5. 实现内存映射文件，提高I/O效率",
                created_at: "2025-04-20T09:15:00Z"
            }
        ]
    } finally {
        loading.value = false
    }
}

// 删除收藏
const deleteCollection = async (collection) => {
    try {
        await ElMessageBox.confirm('确定要删除这个收藏吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}')
        const username = studentInfo.username || studentInfo.stu_id

        await axios.delete(`/api/student/collections/${collection.id}`, {
            params: { username }
        })

        ElMessage.success('收藏删除成功')

        // 从列表中移除删除的收藏
        collections.value = collections.value.filter(item => item.id !== collection.id)
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除收藏失败:', error)
            ElMessage.error('删除收藏失败，请稍后重试')
        }
    }
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 组件挂载时获取数据
onMounted(() => {
    fetchCollections()
})

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <div class="collect-page">
        <el-header style="padding: 20px">
            <el-row>
                <el-col :span="2">
                    <el-icon size="30" color="black" class="clickable">
                        <HomeFilled @click="backToHome"/>
                    </el-icon>
                </el-col>
                <el-col :span="20">
                    <div style="text-align: center; font-size: large">
                        收藏对话
                    </div>
                </el-col>
                <el-col :span="2" />
            </el-row>
        </el-header>

        <el-main>
            <div class="collections-container" v-loading="loading">
                <div v-if="collections.length === 0" class="empty-collections">
                    <el-empty description="暂无收藏" />
                </div>

                <div v-else class="collections-list">
                    <el-card v-for="collection in collections" :key="collection.id" class="collection-card">
                        <template #header>
                            <div class="collection-header">
                                <h3>{{ collection.title || '无标题对话' }}</h3>
                                <div class="collection-actions">
                                    <el-button type="danger" text :icon="Delete" @click="deleteCollection(collection)">
                                        删除
                                    </el-button>
                                </div>
                            </div>
                        </template>

                        <div class="collection-meta">
                            <span>收藏时间：{{ formatDate(collection.created_at) }}</span>
                        </div>

                        <div class="collection-content">
                            {{ collection.content }}
                        </div>
                    </el-card>
                </div>
            </div>
        </el-main>
    </div>
<!--    <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo" class="chat-iframe"></iframe>-->
<!--    </div>-->
</template>

<style scoped>
.collect-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.collections-container {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.collections-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.collection-card {
    margin-bottom: 15px;
}

.collection-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.collection-actions {
    display: flex;
    gap: 10px;
}

.collection-meta {
    color: #666;
    margin-bottom: 15px;
    font-size: 0.9em;
}

.collection-content {
    white-space: pre-wrap;
    line-height: 1.6;
    background: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    margin-top: 10px;
    max-height: 300px;
    overflow-y: auto;
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.empty-collections {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}

.clickable {
    cursor: pointer;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
